<?php

namespace App\Service\Index;

use App\Constants\ErrorCode;
use App\Model\PayOrder;
use App\Model\UserProfile;
use App\Model\VoiceCall;
use App\Model\CallHangup;
use App\Service\CallBaseService;

/**
 * 新手免费拨打语聊
 */
class NewUserCallService extends CallBaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $user = $this->getUser();

        //是否绑定手机号
        if (!$user->phone) {
            return $this->setError(ErrorCode::PHONE_NOT_BIND, '你还没有绑定手机号，请先绑定~');
        }

        //查询充值订单
        $check = PayOrder::checkSuccess($userId);
        if (!$check) {
            return $this->setError(ErrorCode::NO_PAY_NO_BENIFIT, "你还没有首次充值，\n充值任意金额可获取新手免费福利哦！");
        }

        //查询剩余免费时长
        $freeallTime = UserProfile::getFreeCallTime($userId);
        if ($freeallTime < 1) {
            return $this->setError(ErrorCode::REMAIN_TIME_LMT, '你的剩余免费通话时间不够了哦，可以试试一键发起聊天！');
        }

        //获取新手指定的主播
        $hostId = $this->getHostId($userId);
        if (!$hostId) {
            return $this->setError(ErrorCode::NO_VALID_HOST, '当前声优均在忙碌中，请稍后再试~');
        }

        //查询声优资料
        $profile = UserProfile::getProfile($hostId);

        //修改以前无效状态
        VoiceCall::finishOldCall($userId);

        //添加记录
        VoiceCall::addRecord($userId, $hostId, VoiceCall::FROM_NEW);

        //呼叫回调
        $this->callHook($hostId, $userId);

        $ret = UserProfile::buildHostItem($profile);
        // log_info(__CLASS__ . "=={$userId}==" . json_encode($ret));
        log_user_result($userId, $ret);
        return [
            'user_info' => $ret
        ];
    }

    /**
     * 获取匹配主播ID
     */
    function getHostId($userId)
    {
        //推荐声优-女
        $hostIds = UserProfile::getRecHosts(0);
        //排除正在通话的
        $callingHosts = VoiceCall::getCallingHostIds();
        $hostIds = array_diff($hostIds, $callingHosts);
        //排除最近挂断用户的
        $hangupHosts = CallHangup::latestRecords($userId, 3);
        $hostIds = array_values(array_diff($hostIds, $hangupHosts));
        log_user_result($userId, "Calling:" . json_encode($callingHosts) . "==Hangup:" . json_encode($hangupHosts) . "==Hosts:" . json_encode($hostIds));
        if (empty($hostIds)) return 0;
        return $hostIds[array_rand($hostIds)];
    }
}
